package com.tx.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tx.entity.User;
import com.tx.service.UserService;
import com.tx.service.impl.UserServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取表单提交的账号和密码
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        System.out.println("接收到的登录请求 - 账号: " + account + ", 密码: " + password); // 添加调试日志

        // 调用service层进行登录验证
        User user = userService.login(account, password);

        if (user != null) {
            // 登录成功，将用户信息存入session
            HttpSession session = request.getSession();
            session.setAttribute("username", user.getAccount());

            //设置session的过期时间为10分钟
            session.setMaxInactiveInterval(10 * 60);
            // 返回success给前端
            out.print("success");
        } else {
            // 登录失败，返回fail给前端
            out.print("fail");
        }
    }

}